<template>
  <continer class="call-continer" :shadow="false">
    <template slot="search">
      <QuickSearch
        :advForm="quickSearchForm"
        @QuickSearch="getIvrList"
      ></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="pageChange(1)">刷新</el-button>
    </template>
    <template slot="content">
      <configTable
        :headers="tableHeaders"
        :data="tableData"
        :pagingData="pagingData"
        :selection='false'
        @pageChange="pageChange"
        @pageSizeChange="pageSizeChange"
        @checkHeadersChange="checkHeadersChange"
        v-loading="showLoading"
        :headersConfig="false"
        ref="configTabel"
        :batchs="configBatchs"
        @batchClick="batchClick"
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :sortable="item.sortable"
              :show-overflow-tooltip="true"
              v-if="item.prop !== 'lastResult' && item.prop !== 'phone'"
            >
            </u-table-column>
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :sortable="item.sortable"
              v-if="item.show && item.prop === 'phone'"
              align="left"
            >
              <template slot-scope="scope">
                <span class="customerNumber">{{ scope.row.phone | getHideTel }}</span
                ><i
                  class="V7_iconfont V7_iconV7tubiao_tonghua pointer"
                  v-show="visibleDialout"
                  @click="taskDialot(data._id, scope.row.phone)"
                ></i>
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              v-if="item.prop === 'lastResult' && item.show"
              :key="item.label + index"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <div style="display: flex; align-items: center">
                  <span>{{ scope.row.lastResult | getLastResultText }}</span>
                </div>
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue, Prop, Mixins } from 'vue-property-decorator'
import configTable from '@/components/configCommon/table.vue'
import { IvrModule } from '@/store/modules/config/ivr'
import { ElMessageBoxShortcutMethod } from 'element-ui/types/message-box'
import { commonAction, checkHideTel } from '@/utils/common'
import { IvrData, PagingData, TabelHeaders } from '../types/index'
import { CommonModule } from '@/store/modules/common/index'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'

import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'

import taskMixin from '../common/task-mixin'
@Component({
  name: 'ServiceNumber',
  components: { configTable, QuickSearch, continer },
  filters: {
    getHideTel (customerNumber) {
      return checkHideTel(customerNumber)
    },
    getLastResultText (status) {
      let text = '未知状态'
      switch (status) {
        case 'UNDEAL':
          text = '未呼叫'
          break;
        case 'DEALING':
          text = '已接听'
          break;
        case 'NOT_DEAL':
          text = '未接听'
          break;
        default:
          break;
      }
      return text
    }
  }
})
export default class extends Mixins(taskMixin) {
  @Prop({ default: {} }) private data: any
  @Prop({ default: true }) private visibleDialout: boolean | undefined
  private $confirm: ElMessageBoxShortcutMethod | undefined
  private showLoading: boolean = false
  get account () {
    return (this.$store as any).state.common.session.account._id
  }

  private detailsData: any = {}

  private currentPage = 'editOrAdd'

  private isShowPage (page: string) {
    return this.currentPage === page
  }

  private mounted (): void {
    this.getIvrList()
  }

  private stateOptions = [{
    name: '全部',
    _id: ''
  }, {
    name: '未呼叫',
    _id: 'UNDEAL'
  }, {
    name: '已接听',
    _id: 'DEALING'
  }, {
    name: '未接听',
    _id: 'NOT_DEAL'
  }]

  private quickSearchForm = { // 快捷检索数据（时间条件，类型）
    form: {
      custName: '',
      lastResult: ''
    },
    advSearchOptions: [ // 快捷检索的数据(语音文件名称)
      { label: '客户名称', inputType: 'input', placeholder: '请输入客户名称', name: 'custName', clearable: true },
      { label: '外呼结果', inputType: 'select', clearable: true, selectData: this.stateOptions, name: 'lastResult' }
    ]
  }

  // 详情控制
  private showPage: boolean = false

  private pagingData: PagingData = { total: 0, limit: 10, page: 1 }

  private tableHeaders: TabelHeaders[] = [
    {
      label: '客户名称',
      prop: 'custName'
    },
    {
      label: '呼叫座席',
      prop: 'name'
    },
    {
      label: '呼叫电话',
      prop: 'phone'
    },
    {
      label: '备注',
      prop: 'memo'
    },
    {
      label: '呼叫次数',
      prop: 'callCount'
    },

    {
      label: '最后一次呼叫结果',
      prop: 'lastResult'
    }
  ]

  get configBatchs () {
    return [
      { name: '批量导出', action: 'bulkExport', disabled: this.data.status === 'DEALING', tipContent: '在任务进行中时不允许对数据进行操作，如果需要导出或者删除，请暂停或者将任务归档后再进行操作', _id: 'preview_dialout_list_exportData' },
      { name: '批量删除', action: 'bulkDeletion', disabled: this.data.status === 'DEALING', tipContent: '删除只会删除某条数据，并不会删除该数据对应的通话记录', _id: 'preview_dialout_list_deleteData' }
    ]
  }

  private bulkExport (selectedArr) {
    let sendData: any = {}
    if (Array.isArray(selectedArr)) {
      sendData = { ids: selectedArr, taskName: this.data.name }
    } else {
      sendData = {
        condition: {
          ...this.quickSearchForm.form,
          taskId: this.data._id
        },
        taskName: this.data.name
      }
    }
    commonAction({ url: '/call/action/task/export', method: 'post', data: sendData }).then(res => {
      if (res.success) {
        (this.$message as any).success('导出任务创建成功')
      }
    })
  }

  private bulkDeletion (selectedArr) {
    let sendData: any = {}
    if (Array.isArray(selectedArr)) {
      sendData = { ids: selectedArr, taskId: this.data._id }
    } else {
      sendData = {
        condition: {
          ...this.quickSearchForm.form
        },
        taskId: this.data._id
      }
    }
    commonAction({ url: '/call/action/task/batch/delete', method: 'post', data: sendData }).then(res => {
      if (res.success) {
        (this.$message as any).success('删除成功')
      }
    })
  }

  private batchClick (action, selectList) {
    this[action](selectList)
  }

  private checkHeaders: TabelHeaders[] = []
  private tableData: IvrData[] = []

  private pageChange (page: number): void {
    this.pagingData.page = page
    this.getIvrList()
  }

  private handleDeleteById (row: any) {
    const taskId = row._id
    this.handleDelete(taskId).then((success) => {
      if (success) {
        this.getIvrList()
      }
    })
  }

  private pageSizeChange (size: number): void {
    this.pagingData.page = 1
    this.pagingData.limit = size
    this.getIvrList()
  }

  private changeState (row: any, status: string) {
    const taskId = row._id
    const oldStatus = row.status
    row.status = status
    this.updateTaskState(taskId, status).then((success) => {
      if (!success) {
        row.status = oldStatus
      }
    })
  }

  private handleEdit (row): void {
    this.currentPage = 'editOrAdd'
    this.detailsData = row
    this.showPage = true
  }

  private detailsToEdit () {
    if (this.detailsData) {
      this.currentPage = 'editOrAdd'
    }
  }

  private checkdDtails (row: any) {
    this.currentPage = 'details'
    this.detailsData = row
    this.showPage = true
  }

  private checkHeadersChange (checkList): void {
    this.$set(this, 'checkHeaders', checkList)
  }

  private getIvrList (): void {
    this.showLoading = true
    const quickData = {}
    Object.keys(this.quickSearchForm.form).forEach((key) => {
      if (this.quickSearchForm.form[key]) {
        quickData[key] = this.quickSearchForm.form[key]
      }
    })
    const actionData = Object.assign({ limit: this.pagingData.limit, page: this.pagingData.page }, { taskId: this.data._id, account: this.account }, quickData)
    const data = { url: '/call/action/task/data/list', method: 'POST', data: actionData }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      const resList = res.data.list || []
      this.tableData = resList
      this.pagingData.total = res.data.count || 0
      this.showLoading = false
    })
  }

  public get userList (): any {
    return CommonModule.publicCache.userListObj
  }
}
</script>

<style lang="stylus" scoped>
.customerNumber
  margin-right 9px
.customerNumber + .V7_iconfont
  color #bebec4
  font-size 12px
.tabel
  height calc(100% - 90px)
.detail
  .col
    display flex
    flex-direction column
    font-weight bold
    font-size 24px
    color #303753
    .list-tit
      font-size 12px
      color #767E91
      margin-bottom 5px
</style>
